import React from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import _ from 'lodash';

import * as Sys from './sys';
import * as SysApi from './sys.api';
import * as SysBom from './sys.bom';
import * as SysDom from './sys.dom';
import { TextBox, PasswordBox } from './components/text-box';
import { Form } from './components/forms';
import { LoginButton } from './components/buttons';
import * as SignInApi from './components/sign-in';
import { Content, PageTitle } from './components/content';


SignInApi.register();

interface IApp {
    errorCode?: number,
}

class App extends React.Component<{}, IApp> {
    private loginNameOrMobileRef: React.RefObject<TextBox> = React.createRef();
    private passwordRef: React.RefObject<PasswordBox> = React.createRef();

    constructor(props: {}) {
        super(props);

        this.state = {
            errorCode: 0,
        };
    }

    private handleSubmit = (evt: React.MouseEvent<HTMLButtonElement>): void => {
        this.setState({
            errorCode: 0,
        });

        SysApi.call('security.signIn',
            {
                username: this.loginNameOrMobileRef.current.getValue(),
                password: this.passwordRef.current.getValue(),
            }, true)
            .then(() => SysBom.jumpTo(Sys.urlSafeAtob(SysBom.parseSearch().return) || '/'))
            .catch(err => {
                this.passwordRef.current.setValue().focus();
                this.setState({
                    errorCode: err.code,
                });
            });
    };

    shouldComponetUpdate = (nextProps: {}, nextState: IApp) => !_.isEqual(nextState, this.state);

    render = (): JSX.Element => {
        const hasError = this.state.errorCode !== 0;
        return <div className="ui middle aligned center aligned grid">
            <div className="column" style={{ maxWidth: '32rem' }}>
                <Content>
                    <PageTitle style={{ fontVariant: 'small-caps' }} >Book store</PageTitle>
                    <Form className={classNames('ui large form', { error: hasError })}>
                        <div className="ui stack segment">
                            <TextBox inline={false} placeholder="登录名" required={true} autoFocus={true} maxLength={40} icon="user" ref={this.loginNameOrMobileRef} />
                            <PasswordBox type="password" inline={false} placeholder="口令" required={true} maxLength={20} icon="lock" ref={this.passwordRef} />
                            <LoginButton className="ui fluid primary button" onClick={this.handleSubmit} />
                            {hasError ?
                                <div className="ui error message">
                                    <div className="header">登录失败</div>
                                    <p>登录名或口令不正确。</p>
                                </div>
                                : null
                            }
                        </div>
                        <div className="ui segment">
                            放弃登录？您可以<a href={(window as any).env.base + '/'}>回到首页</a>
                        </div>
                    </Form>
                </Content>
            </div>
        </div >;
    };
}

Sys.ready(() => ReactDOM.render(<App />, document.getElementById('root')!));